package com.tipfy.tmx;


class TiledProperties
{
    /**
     *
     */
    private var _properties:Map<String,String>;

    /**
     * Constructor.
     */
    public function new(xml:Xml)
    {
        // Child elements.
        for (elem in xml.elements())
        {
            this._loadProperty(elem);
        }

        // Some elements must occur at least once.
        if (this._properties == null)
        {
            throw "Missing element <property>.";
        }
    }

    /**
     * <property>. minOccurs="1", maxOccurs="unbounded"
     */
    private function _loadProperty(xml:Xml):Void
    {
        if (this._properties == null)
        {
            this._properties = new Map<String,String>();
        }

        if (xml.nodeName != "property")
        {
            throw "Only <property> tag is allowed inside <properties>.";
        }

        // Values can be empty, names can't.
        var name:String = TiledAttributes.getNonEmpty(xml, "name");
        var value:String = TiledAttributes.get(xml, "value");

        this._properties.set(name, value);
    }

    /**
     *
     */
    public function get(key:String, ?defaultValue:String=null):String
    {
        var value:String = this._properties.get(key);

        if (value == null && defaultValue != null)
        {
            return defaultValue;
        }

        return value;
    }

    /**
     *
     */
    public function getBool(key:String, ?defaultValue:Bool=false):Bool
    {
        var value:String = this._properties.get(key);

        if (value == null && defaultValue != null)
        {
            return defaultValue;
        }

        if (value == "1")
        {
            return true;
        }

        return false;
    }

    /**
     *
     */
    public function getFloat(key:String, ?defaultValue:Float=null):Float
    {
        var value:String = this._properties.get(key);

        if (value == null && defaultValue != null)
        {
            return defaultValue;
        }

        return Std.parseFloat(value);
    }

    /**
     *
     */
    public function getInt(key:String, ?defaultValue:Int=null):Int
    {
        var value:String = this._properties.get(key);

        if (value == null && defaultValue != null)
        {
            return defaultValue;
        }

        return Std.parseInt(value);
    }
}